package com.wyvoid.forum.web.action.controlPanel;

import com.wyvoid.forum.web.action.BaseAction;
import com.wyvoid.forum.annotations.LoginUser;
import com.wyvoid.forum.domain.User;
import com.wyvoid.forum.service.IUserService;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.Validate;

/**
 * Created by IntelliJ IDEA.
 * User: wangchao
 * Date: 2007-7-1
 * Time: 14:48:30
 * To change this template use File | Settings | File Templates.
 */
@UrlBinding("/controlPanel/updatePassword.do")
@LoginUser
public class UpdatePasswordAction extends BaseAction {
    @SpringBean
    private IUserService userService;

    private User oldUser;
     @ValidateNestedProperties({
          @Validate(field = "oldPassword", required = true, minlength = 5, maxlength = 20),
          @Validate(field = "newPassword", required = true, minlength = 5, maxlength = 20),
          @Validate(field = "confirmPassword", required = true, minlength = 5, maxlength = 20),
          @Validate(expression = "this == user.password")
             })
    private String oldPassword;
    private String newPassword;
    private String confirmPassword;

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }


    public User getOldUser() {
        return oldUser;
    }

    public void setOldUser(User oldUser) {
        this.oldUser = oldUser;
    }

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    @DontValidate
     @DefaultHandler
    public Resolution updatePasswordForm() {
        oldUser = userService.getUser(getContext().getUserId());
        return getBBSResolution("controlPanel/updatePasswordForm");
    }

    public Resolution updatePassword() {
        User updateUser = userService.getUser(getContext().getUserId());
        if (oldPassword.equals(updateUser.getPassword())) {
            if (newPassword.equals(confirmPassword)) {
                updateUser.setPassword(newPassword);
                userService.updateUser(updateUser);
                return new RedirectResolution("success", false);
            }
        }
        return new RedirectResolution("/");

    }
}
